package com.taugin.wechatreader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.taugin.wechatreader.info.WxContactInfo;
import com.taugin.wechatreader.iview.IView;
import com.taugin.wechatreader.presenter.WxReaderPresenter;
import com.taugin.wechatreader.utils.Log;
import com.taugin.wechatreader.utils.Utils;

import java.util.List;

public class MainActivity extends AppCompatActivity implements IView {

    private RecyclerView mRecyclerView;
    private MainAdapter mAdapter;
    private WxReaderPresenter mPresenter;
    private ProgressDialog mProgressDialog;
    public static final String SQL_QUERY_CONTACT_AND_IMG = "" +
            "SELECT rcontact.username, alias, conRemark, nickname, reserved1, reserved2 from rcontact left join img_flag on rcontact.username=img_flag.username where verifyFlag = 0 and type != 4 and type != 2 and nickname != '' limit 20, 9999";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.destroy();
        }
    }

    private void initView() {
        mRecyclerView = (RecyclerView) findViewById(R.id.list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration decoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        mRecyclerView.addItemDecoration(decoration);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        mAdapter = new MainAdapter(this);
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.setOnCreateContextMenuListener(this);
    }

    private void initData() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mPresenter = new WxReaderPresenter(this);
        mPresenter.connectDatabase();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1, 1, 1, "刷新");
        menu.add(1, 2, 2, "查看密码");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            refresh();
            return true;
        } else if (item.getItemId() == 2) {
            String password = Utils.getString(this, "password");
            showAlert("数据库密码：" + password);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo mInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
        WxContactInfo info = mAdapter.getItem(mInfo.position);
        if (info == null) {
            return;
        }

        String title = null;

        title = info.getUserName();
        menu.add(1, ContextMenu.FIRST + 1, 1, "复制用户名").setEnabled(!TextUtils.isEmpty(title));

        title = info.getAlias();
        menu.add(1, ContextMenu.FIRST + 2, 1, "复制别名").setEnabled(!TextUtils.isEmpty(title));

        title = info.getNickName();
        menu.add(1, ContextMenu.FIRST + 3, 1, "复制昵称").setEnabled(!TextUtils.isEmpty(title));

        menu.add(1, ContextMenu.FIRST + 4, 1, "查看头像").setEnabled(!TextUtils.isEmpty(info.getIcon())
                || !TextUtils.isEmpty(info.getIcon2()));

        if (menu.size() > 0) {
            menu.setHeaderTitle(title);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        Log.i(Log.TAG, "position = "+menuInfo.position);
        WxContactInfo info = mAdapter.getItem(menuInfo.position);
        if (info == null) {
            return true;
        }
        if (item.getItemId() == ContextMenu.FIRST + 1) {
            copyString(info.getUserName());
        } else if (item.getItemId() == ContextMenu.FIRST + 2) {
            copyString(info.getAlias());
        } else if (item.getItemId() == ContextMenu.FIRST + 3) {
            copyString(info.getNickName());
        } else if (item.getItemId() == ContextMenu.FIRST + 4) {
            showPhoto(TextUtils.isEmpty(info.getIcon()) ? info.getIcon2() : info.getIcon());
        }
        return true;
    }

    private void copyString(String str) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            android.content.ClipboardManager manager = (android.content.ClipboardManager) getSystemService(Activity.CLIPBOARD_SERVICE);
            if (manager != null) {
                ClipData clip = ClipData.newPlainText("text", str);
                manager.setPrimaryClip(clip);
            }
        } else{
            @SuppressWarnings("deprecation")
            android.text.ClipboardManager manager = (android.text.ClipboardManager) getSystemService(Activity.CLIPBOARD_SERVICE);
            if (manager != null) {
                manager.setText(str);
            }
        }
        Toast.makeText(this, "[" + str + "]已复制", Toast.LENGTH_SHORT).show();
    }

    private void showPhoto(final String url) {
        final Dialog photoDialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar);
        final ImageView imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        showImage(url, imageView, R.mipmap.ic_launcher);
        photoDialog.setContentView(imageView);
        photoDialog.show();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photoDialog.dismiss();
            }
        });
    }

    private void refresh() {
        Utils.putString(this, "wx_database", null);
        Utils.putString(this, "password", null);
        mPresenter.connectDatabase();
    }

    private void showAlert(final String msg) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("信息");
        builder.setMessage(msg);
        builder.setPositiveButton("确定", null);
        builder.create().show();
    }

    @Override
    public void showProgress() {
        mProgressDialog.show();
    }

    @Override
    public void updateProgress(String msg) {
        if(mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.setMessage(msg);
        }
    }

    @Override
    public void hideProgress() {
        if(mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onReadContact(List<WxContactInfo> list) {
        Log.d(Log.TAG, "list : " + (list != null ? list.size() : 0));
        setTitle(getResources().getString(R.string.app_name) + "("+(list != null ? list.size() : 0)+")");
        mAdapter.setData(list);
    }

    @Override
    public void showErrorMsg(String msg) {
        showAlert(msg);
    }

    @Override
    public Context getContext() {
        return getBaseContext();
    }

    class MainAdapter extends RecyclerView.Adapter<MyViewHolder> implements View.OnLongClickListener {

        private Context mContext;
        private List<WxContactInfo> mList;
        private boolean longPressing = false;

        public MainAdapter(Context context) {
            mContext = context;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(mContext)
                    .inflate(R.layout.wx_contact_item, null);
            itemView.setLongClickable(true);
            itemView.setOnLongClickListener(this);
            MyViewHolder viewHolder = new MyViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, int position) {
            WxContactInfo info = mList.get(position);
            if (info == null) {
                return;
            }
            String alias = info.getAlias();
            String uName = info.getUserName();
            String nName = info.getNickName();
            holder.textView1.setText(mContext.getResources().getString(R.string.username, uName));
            holder.textView2.setText(mContext.getResources().getString(R.string.wx_alias, alias));
            holder.textView3.setText(mContext.getResources().getString(R.string.nickname, nName));

            String icon = info.getIcon2();
            if (TextUtils.isEmpty(icon)) {
                icon = info.getIcon();
            }
            showImage(icon, holder.imageView, R.mipmap.ic_launcher);
        }

        @Override
        public int getItemCount() {
            return mList != null ? mList.size() : 0;
        }

        public void setData(List<WxContactInfo> list) {
            mList = list;
            this.notifyDataSetChanged();
        }

        public WxContactInfo getItem(int position) {
            if (mList != null) {
                return mList.get(position);
            }
            return null;
        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private ImageView imageView;
        private TextView textView1;
        private TextView textView2;
        private TextView textView3;

        public MyViewHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.imageView);
            textView1 = (TextView) itemView.findViewById(R.id.textView1);
            textView2 = (TextView) itemView.findViewById(R.id.textView2);
            textView3 = (TextView) itemView.findViewById(R.id.textView3);
            textView1.setSingleLine();
            textView1.setEllipsize(TextUtils.TruncateAt.END);
            textView2.setSingleLine();
            textView2.setEllipsize(TextUtils.TruncateAt.END);
            textView3.setSingleLine();
            textView3.setEllipsize(TextUtils.TruncateAt.END);
        }
    }

    private void showImage(String url, final ImageView imageView, final int defaultId) {
        ImageLoader.getInstance().displayImage(url, imageView, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                imageView.setImageResource(defaultId);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                if (loadedImage == null) {
                    imageView.setImageResource(defaultId);
                }
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                imageView.setImageResource(defaultId);
            }
        });
    }
}
